﻿using System;
using System.Web;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.AspNet.Membership.OpenAuth;
using PaymentBLL;

public partial class Account_RegisterExternalLogin : System.Web.UI.Page
{
    public string ProviderDisplayName = "";
    public string ProviderUserName = "";
    protected void Page_Load()
    {
        if (!IsPostBack)
        {
            ProcessProviderResult();
        }
    }

    private void ProcessProviderResult()
    {
        // Process the result from an auth provider in the request
        var providerName = OpenAuth.GetProviderNameFromCurrentRequest();

        if (String.IsNullOrEmpty(providerName))
        {
            Response.Redirect(FormsAuthentication.LoginUrl);
        }

        ProviderDisplayName = OpenAuth.GetProviderDisplayName(providerName);

        // Build the redirect url for OpenAuth verification
        var redirectUrl = "~/Account/RegisterExternalLogin.aspx";
        var returnUrl = Request.QueryString["ReturnUrl"];
        if (!String.IsNullOrEmpty(returnUrl))
        {
            redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
        }

        // Verify the OpenAuth payload
        var authResult = OpenAuth.VerifyAuthentication(redirectUrl);
        
        ProviderUserName = authResult.UserName;

        if (!authResult.IsSuccessful)
        {
            Title = "External login failed";
            userNameForm.Visible = false;
            
            providerMessage.Text = String.Format("External login {0} failed,", ProviderDisplayName);
            
            // To view this error, enable page tracing in web.config (<system.web><trace enabled="true"/></system.web>) and visit ~/Trace.axd
            Trace.Warn("OpenAuth", String.Format("There was an error verifying authentication with {0})", ProviderDisplayName), authResult.Error);
            return;
        }

        // User has logged in with provider successfully
        // Check if user is already registered locally
        var ctr = new CtrAccount();
        string uName = authResult.UserName;
        string fName = authResult.UserName;
        var info = ctr.SelectAccountInfoByName(uName);
        if(info!=null)
        {
            AccountSession.Login(info.Id, uName, fName, GetProviderKeyByName(providerName));
            RedirectToReturnUrl();
        }

        int? id = 0;
        ctr.InsertAccount(uName, fName, GetProviderKeyByName(providerName),
            ProviderDisplayName, "", 1, ref id);
        if (!(id>0))
        {
            userNameMessage.Text = "Lỗi tạo tài khoản";
        }
        else
        {
            AccountSession.Login(id ?? 0, uName, fName, GetProviderKeyByName(providerName));
            RedirectToReturnUrl();
        }        
    }
    private int GetProviderKeyByName(string name)
    {
        switch (name)
        {
            
            case "facebook":
                return 2;
            case "google":
                return 3;
            case "yahoo":
                return 4;
            case "twitter":
                return 5;
            case "Govn":
                return 6;
        }
        return 0;
    }    

    private void RedirectToReturnUrl()
    {
        var returnUrl = Request.QueryString["ReturnUrl"];
        if (!String.IsNullOrEmpty(returnUrl) && OpenAuth.IsLocalUrl(returnUrl))
        {
            Response.Redirect(returnUrl);
        }
        else
        {
            Response.Redirect("~/");
        }
    }
}